package remote_work.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

import remote_work.dto.InputObject;
import remote_work.dto.OutputObject;
import remote_work.util.MyClassLoader;

/**
 * @author LiuPing
 *
 * 2018年3月20日
 */
public class TaskService implements Runnable {
	
	private Socket socket;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;
	
	public TaskService(Socket socket) {
		this.socket = socket;
	}
	
	
	@Override
	public void run() {
		
		OutputObject outputObject = new OutputObject();
		try {
			ois = new ObjectInputStream(socket.getInputStream());
			InputObject inputObject = (InputObject) ois.readObject();
			String methodName = inputObject.getMethod();
			if (methodName == null || "".equals(methodName)) {
				outputObject.setReturnCode("-1");
				outputObject.setReturnMessage("方法名错误");
			} else {
				String className = MyClassLoader.getQualifiedClassName(methodName);
//				if (className == null || "".equals(className)) {
//					outputObject.setReturnCode("-1");
//					outputObject.setReturnMessage("调用方法出错");
//				} else {
					Class<?> cls = Class.forName(className);
					Method method = cls.getMethod(methodName, InputObject.class);
					outputObject = (OutputObject) method.invoke(cls.newInstance(), inputObject);
//				}
			}
			oos = new ObjectOutputStream(socket.getOutputStream());
			oos.writeObject(outputObject);
			oos.flush();
		} catch (Exception e) {
			e.printStackTrace();
			outputObject.setReturnCode("-9999");
			outputObject.setReturnMessage("调用方法出错");
		}
		
	}
	
}
